const solc = require('solc'), fs = require('fs'),
    Web3 = require('web3'), cfg = require('../config'),
    web3 = new Web3(new Web3.providers.HttpProvider(cfg.providers));
const { logger } = require('./logger');
/**
 * use http protocol deployed contracts
 * add by: martin
 * date:2018-06-30
 * params.name: token name
 * params.symbol:token symbol
 * params.decimals:token decimals
 * params.total: init token total 
 */
let deployed = async (params) => {
    try {
        let source = fs.readFileSync('./contracts/Token.sol', 'utf8');
        let compiledContract = solc.compile(source, 1);
        // console.log(compiledContract);

        let abi = compiledContract.contracts[':Token'].interface;
        let bytecode = compiledContract.contracts[':Token'].bytecode;
        let gasEstimate = await web3.eth.estimateGas({ data: bytecode });

        let coinbase = await web3.eth.getCoinbase();
        logger.info('coinbase:', coinbase);
        logger.info('coinbase balance:', await web3.eth.getBalance(coinbase));

        const myContractIns = await new web3.eth.Contract(
            JSON.parse(abi),
            // MyContract.networks[MY_NETWORK_ID].address,
            { from: coinbase, gas: 21000, gasPrice: 20000000000 }
        )
        //deploy contracts
        return new Promise((resolve, reject) => {
            myContractIns.deploy({
                data: bytecode,
                arguments: [params.name, params.symbol, params.decimals, params.total]
            }).send({
                from: coinbase, //msg.sender
                // nonce: 28613,
                gasPrice: 20000000000,
                gas: gasEstimate * 2,
            }, (error, transactionHash) => {
                if (error) {
                    logger.error('error=>', error)
                } else {
                    logger.info('transactionHash=>', transactionHash)
                }
            })
                .on('error', function (error) {
                    logger.error('deploy event error:==>', error)
                })
                .on('transactionHash', (transactionHash) => {
                    web3.eth.getTransaction(transactionHash).then(tx => logger.info('getTransaction:', tx))
                })// contains the transactionHash
                .on('receipt', function (receipt) {
                    logger.info('deploy event receipt contractAddress:=>', receipt.contractAddress) // contains the new contract address
                })
                .on('confirmation', function (confirmationNumber, receipt) {
                    logger.info('deploy event confirmation confirmationNumber:=>', confirmationNumber)
                })
                .then((newContractInstance) => {
                    logger.info('newContractInstance address:', newContractInstance.options.address) // instance with the new contract address
                    resolve(newContractInstance.options.address);
                });
        });

    } catch (error) {
        logger.error('deployed contract err:', error) //error
        return error;
    }

}
/**
 * use http protocol getBalance of ERC20 tokens
 * add by: martin
 * date:2018-07-12
 * ctrt_address: address of contractx
 */
// let getBalance = async (ctrt_address) => {
//     try {
//         let source = fs.readFileSync('./contracts/Token.sol', 'utf8');
//         let compiledContract = solc.compile(source, 1);

//         let abi = compiledContract.contracts[':Token'].interface;
//         let bytecode = compiledContract.contracts[':Token'].bytecode;
//         let gasEstimate = await web3.eth.estimateGas({ data: bytecode });

//         let coinbase = await web3.eth.getCoinbase();
//         console.log('coinbase:', coinbase);
//         console.log('coinbase balance:', await web3.eth.getBalance(coinbase));

//         const myContractIns = await new web3.eth.Contract(
//             JSON.parse(abi),
//             ctrt_address,
//             // MyContract.networks[MY_NETWORK_ID].address,
//             { from: coinbase, gas: gasEstimate * 2, gasPrice: 20000000000 }
//         )
//         //call getbalance method
//         return new Promise(async (resolve, reject) => {
//             let balance = await myContractIns.methods.balanceOf(coinbase).call(), ///// msg.sender is from address !!!!!!!
//                 name = await myContractIns.methods.name().call(),
//                 symbol = await myContractIns.methods.symbol().call(),
//                 decimals = await myContractIns.methods.decimals().call()
//             resolve({ balance: balance, name: name, symbol: symbol, decimals: decimals });
//         });

//     } catch (error) {
//         console.log('deployed contract err:', error) //error
//         return error;
//     }

// }
// /**
//  * use http protocol transfer to address of contract,not transfer to address of ethereum 
//  * add by: martin
//  * date:2018-07-12
//  * ctrt_address: address of contractx
//  * to_address: address of contractx 
//  * amount: transfer to amount 
//  */
// let transfer = async (ctrt_address, to_address, amount) => {
//     try {
//         let source = fs.readFileSync('./contracts/Token.sol', 'utf8');
//         let compiledContract = solc.compile(source, 1);

//         let abi = compiledContract.contracts[':Token'].interface;
//         let bytecode = compiledContract.contracts[':Token'].bytecode;
//         let gasEstimate = await web3.eth.estimateGas({ data: bytecode });

//         let coinbase = await web3.eth.getCoinbase();
//         console.log('coinbase:', coinbase);
//         console.log('coinbase balance:', await web3.eth.getBalance(coinbase));

//         const myContractIns = await new web3.eth.Contract(
//             JSON.parse(abi),
//             ctrt_address,
//             // MyContract.networks[MY_NETWORK_ID].address,
//             { from: coinbase, gas: gasEstimate * 2, gasPrice: 20000000000 }
//         )
//         //call getbalance method
//         return new Promise(async (resolve, reject) => {
//             let transfer = await myContractIns.methods.transfer(to_address, amount)
//             // .send({
//             //     from: coinbase,
//             //     gasPrice: 20000000000,
//             //     gas: (gasEstimate * 2),
//             //     value :amount
//             // });
//             resolve(transfer);
//         });

//     } catch (error) {
//         console.log('transfer err:', error) //error
//         return error;
//     }

// }
module.exports = { deployed }